//
//  AgreeViewController.m
//  LeagueOfLegend
//
//  Created by cc on 14-7-10.
//  Copyright (c) 2014年 cc. All rights reserved.
//

#import "AgreeViewController.h"
#import "FilesOperation.h"
#import <AVOSCloud/AVOSCloud.h>
#import "Request.h"
#import "RegisterViewController.h"
#import <AdSupport/ASIdentifierManager.h>
#import "MobClick.h"
#define Kwidth self.view.frame.size.width

#define Kheight self.view.frame.size.height

@interface AgreeViewController ()

@end

@implementation AgreeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _array = [[NSMutableArray alloc] initWithCapacity:0];
//    UIImageView *imageView = [[UIImageView alloc] init];
//    imageView.backgroundColor = [UIColor redColor];
//    [self.view addSubview:imageView];
    
    self.titleLab.text = @"聊天室";
    [self.rigthButton setTitle:@"昵称" forState:UIControlStateNormal];
    [self.rigthButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.rigthButton addTarget:self action:@selector(navigationRightButtonClick:)
               forControlEvents:UIControlEventTouchUpInside];
    [self addChatFramework];
    // 创建表
    [self creadBackgroundView];
    //刷新数据源
    [self freashData];
    
    //注册通知,监听键盘弹出事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册通知,监听键盘消失事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    
    //为滚动视图添加手势
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(handleSingle:)];
    singleTap.delegate= self;
    singleTap.cancelsTouchesInView = NO;
    [scrBg addGestureRecognizer:singleTap];
    
    if (version>7){
        if (Kheight == 658) {
            _tabForMessage.frame = CGRectMake(0, 64, Kwidth, Kheight - 49 -64 - 68);
//            imageView.frame = CGRectMake(0, 64, Kwidth, 0.5);
        }else{
            _tabForMessage.frame = CGRectMake(0, 64, Kwidth, Kheight - 49 - 64 - 68);
//            imageView.frame = CGRectMake(0, 64, Kwidth, 0.5);
        }
        
    }else{
        _tabForMessage.frame = CGRectMake(0, 24, Kwidth, self.view.frame.size.height - 49- 44 - 68);
//        imageView.frame = CGRectMake(0, 24, Kwidth, 0.5);
         //willSendMsg.frame = CGRectMake(0, Kheight-68-49-20, Kwidth, 68);
    }


}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"AgreeViewController"];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"AgreeViewController"];
}

#pragma mark -- 添加聊天框架
//  创建控件
-(void)addChatFramework
{
    //最下面的“发消息”按钮
    willSendMsg = [[UIView alloc] init];
    willSendMsg.backgroundColor = [UIColor whiteColor];
    willSendMsg.userInteractionEnabled = YES;
    [self.view addSubview:willSendMsg];
    
    //最下面的发送消息输入框等内容
    didSendMsg = [[UIView alloc] initWithFrame:CGRectMake(0, -20, 320, 68)];
    didSendMsg.backgroundColor = [UIColor whiteColor];
    didSendMsg.hidden = YES;
    // 小黑线
    UIView *granyLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)];
    granyLine.backgroundColor = [UIColor colorWithRed:0.87 green:0.87 blue:0.87 alpha:1];
    [willSendMsg addSubview:didSendMsg];
    [willSendMsg addSubview:granyLine];
    
    // 输入框
    _txContent = [[UITextField alloc] initWithFrame:CGRectMake(8, 15, 256, 35)];
    _txContent.delegate = self;
    //[txContent addTarget:self action:@selector(willSendContentToServer:) forControlEvents:UIControlEventEditingDidEndOnExit];
    _txContent.backgroundColor = [UIColor whiteColor];
    _txContent.layer.borderColor =[UIColor colorWithRed:0.87 green:0.87 blue:0.87 alpha:1].CGColor;
    _txContent.layer.borderWidth = 1;
    _txContent.keyboardType = UIKeyboardTypeDefault;
    [_txContent.layer setCornerRadius:10];
    [willSendMsg addSubview:_txContent];
    
    // 发送的按钮
    UIButton *senderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    senderButton.frame = CGRectMake(270, 20, 38, 24);
    [senderButton setTitle:@"发送" forState:UIControlStateNormal];
    [senderButton setTitleColor:[UIColor colorWithRed:0.32 green:0.34 blue:1 alpha:1]
                       forState:UIControlStateNormal];
    senderButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [senderButton addTarget:self action:@selector(sendContentToServer:)
           forControlEvents:UIControlEventTouchUpInside];
    [willSendMsg addSubview:senderButton];
    if (version>=7){
        willSendMsg.frame = CGRectMake(0, Kheight - 64 - 49, Kwidth, 68);
    }else{
        willSendMsg.frame = CGRectMake(0, Kheight-68-49-20, Kwidth, 68);
    }
}

//刷新数据源
-(void)freashData{
    
    _nickNameArr = [[NSMutableArray alloc] initWithCapacity:0];
    _timeArr = [[NSMutableArray alloc] initWithCapacity:0];
    //AVQuery* query = [[AVQuery alloc]initWithClassName:@"talking"];
    AVQuery *query = [AVQuery queryWithClassName:@"talking"];
    [query orderByDescending:@"createdAt"];// 最近的时间在上面
    //[query orderByAscending:@"createdAt"];
//    query.limit = 100;
//    query.skip = 30;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        _nickNameArr = [NSMutableArray arrayWithArray:objects];
//        NSLog(@"&&&&&&&&&&&&&&&&&&&&&%@",_nickNameArr);
        [_nickNameArr removeAllObjects];
        for (int i = objects.count-1; i>=0; i--) {
            [_nickNameArr addObject:[objects objectAtIndex:i]];
            [_timeArr addObject:[objects objectAtIndex:i]];
            [_contentTalkingArr addObject:[objects objectAtIndex:i]];
        }
        
        
        [_tabForMessage reloadData];
        if (version >=7) {
            if (Kheight == 568) {
                _tabForMessage.contentOffset = CGPointMake
                (0, _tabForMessage.contentSize.height-568+68+49+64);
            }else{
                _tabForMessage.contentOffset = CGPointMake
                (0, _tabForMessage.contentSize.height-568+68+49+64+80);
            }
        }
        else{
            _tabForMessage.contentOffset = CGPointMake
            (0, _tabForMessage.contentSize.height-568+68+49+64+80);
        }
               //动画倒最后一行
        //[self scrollTableToFoot:YES];
    }];
    
}
//创建聊天的背景
-(void)creadBackgroundView
{
    _tabForMessage = [[UITableView alloc]init];
    _tabForMessage.delegate = self;
    _tabForMessage.dataSource=self;
    _tabForMessage.rowHeight = 80;
    _tabForMessage.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_tabForMessage];
    [self.view insertSubview:_tabForMessage atIndex:1];

    
}
#pragma mark - 表代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_nickNameArr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:cellIndentifier];
    }else {
        for (UIView *view in [cell.contentView subviews]) {
            [view removeFromSuperview];
        }
    }
    
    
    UIView *view_bg = [[UIView alloc]initWithFrame:cell.frame];
    view_bg.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = view_bg;
    
    
    if (indexPath.row < _nickNameArr.count) {
        AVObject* objiec = [_nickNameArr objectAtIndex:indexPath.row];
        
        // 昵称
        UILabel *txtName = [[UILabel alloc] init];
        txtName.text = [objiec objectForKey:@"nickname"];
//        NSLog(@"+++++++++++++++++++++%@",txtName.text);
        txtName.textColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.76 alpha:1];
        txtName.font = [UIFont systemFontOfSize:14];
        [cell.contentView addSubview:txtName];
        
        // 聊天的时间
        UILabel *txtTime = [[UILabel alloc] init];
        NSDate *timeDate = objiec.createdAt;
        txtTime.text = [self stringFromDate:timeDate];
        txtTime.font = [UIFont italicSystemFontOfSize:11];
        txtTime.textColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.76 alpha:1];
        [cell.contentView addSubview:txtTime];
        
        //        // 聊天的内容
        //        UILabel *txtContent = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 280, 45)];
        //        txtContent.text = [objiec objectForKey:@"content"];
        //        txtContent.numberOfLines = 0;
        //        [cell.contentView addSubview:txtContent];
        
        if ([[objiec objectForKey:@"nickname"] isEqual:[[NSUserDefaults standardUserDefaults]
                                                        objectForKey:@"name"]]) {
            txtName.frame = CGRectMake(260, 5, 50, 20);
            txtName.textAlignment = NSTextAlignmentRight;
            txtTime.frame = CGRectMake(70, 5, 200, 20);
            txtTime.textAlignment = NSTextAlignmentRight;
        }else{
            txtName.frame = CGRectMake(10, 5, 50, 20);
            txtName.textAlignment = NSTextAlignmentLeft;
            txtTime.frame = CGRectMake(70, 5, 200, 20);
            txtTime.textAlignment = NSTextAlignmentLeft;
            
        }
        [cell.contentView addSubview:[self createBubbleWithText:[objiec objectForKey:@"content"]
                                                            get:indexPath.row]];
//        NSLog(@"+++++++++++++++++++++%@",txtName.text);
    }
    return cell;
}
- (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
    
}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSLog(@"as");
    return 90;
    //    UIView *bubble = [_nickNameArr objectAtIndex:indexPath.row];
    //    return bubble.frame.size.height;
}
#pragma mark - 表代理 end
#pragma mark -- buttonClick
//点击昵称的按钮
-(void)navigationRightButtonClick:(UIButton *)sender
{
    RegisterViewController *regist = [[RegisterViewController alloc] init];
    [self presentViewController:regist animated:YES completion:nil];
    [MobClick event:@"AgreeVCNickname"];
}
#pragma mark-- 发送消息的按钮
// 点击确定 发送消息的按钮
-(void)sendContentToServer:(UIButton *)sender
{
    if ([_txContent.text isEqualToString:@""]) {
        UIAlertView *alrtView = [[UIAlertView alloc]initWithTitle:@"温馨提示"
                                                          message:@"您还没有输入内容哦"
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
        [alrtView show];
    }else if(_txContent.text.length >= 140){
        UIAlertView *alrtView = [[UIAlertView alloc]initWithTitle:@"温馨提示"
                                                          message:@"输入信息不能超过140个字哦"
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
        [alrtView show];
    }else{
        if ([Request checkNet]) {
            //发送留言
            //姓名
            //            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            //            NSString *name = [userDefaults objectForKey:@"name"];
            _userName = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
            if (_userName==nil) {
                UIAlertView *alrtView = [[UIAlertView alloc]initWithTitle:@"温馨提示"
                                                                  message:@"您还没有注册昵称哦"
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                        otherButtonTitles:@"确定",nil];
                [alrtView show];
                //[self navigationRightButtonClick:nil];
                //return;
            }else{
                AVACL *acl = [AVACL ACL];
                [acl setPublicReadAccess:YES]; //此处设置的是所有人的可读权限
               
                //内容
                AVObject *nameObject = [AVObject objectWithClassName:@"talking"];
                nameObject.ACL=acl;
                
//                [nameObject setPublicReadAccess:YES];
                [nameObject setObject:_userName forKey:@"nickname"];
                [nameObject setObject:_txContent.text forKey:@"content"];
                [nameObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                     //NSString *message = [NSString stringWithFormat:@"%@\n%@",_txContent.text];
                    //发送成功
                    //刷新
                    
                    [self freashData];
                    [_txContent resignFirstResponder];
                    _txContent.text = @"";
                }];
                
            }
            
        }
        
    }
    [MobClick event:@"AgreeVCSure"];
    
    
}
// 根据文字的内容去创建一个气泡
- (UIView *)createBubbleWithText:(NSString *)message get:(NSInteger)indexpath
{
    // 气泡view
    UIView *view = [[UIView alloc] init];
    view.tag = 2;
    
    UIFont *font = [UIFont systemFontOfSize:14];
    //让一段字符串 根据换行模式和字体强制的去适应一个大小
    CGSize size = [message sizeWithFont:font constrainedToSize:CGSizeMake(300, 1000000) lineBreakMode:NSLineBreakByCharWrapping];
    
    // 设置气泡的图片
    //UIImage *image = [UIImage imageNamed:[[NSUserDefaults standardUserDefaults]objectForKey:@"name"] ? @"bubbleSelf" : @"bubbleG"];
    AVObject* objiec = [_nickNameArr objectAtIndex:indexpath];
    
    if ([[objiec objectForKey:@"nickname"] isEqual:[[NSUserDefaults standardUserDefaults]objectForKey:@"name"]]) {
        view.frame = CGRectMake(100, 35, 220, size.height + 20);
        UIImage *image = [UIImage imageNamed:@"qipao2"];
        // 把一张图片设置成可拉伸的  (边帽)
        UIImage *newImage = [image stretchableImageWithLeftCapWidth:20 topCapHeight:0];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 220, size.height + 20)];
        imageView.image = newImage;
        [view addSubview:imageView];
    }
    else{
        view.frame = CGRectMake(0, 35, 220, size.height + 20);
        UIImage *image = [UIImage imageNamed:@"qipao1"];
        // 把一张图片设置成可拉伸的  (边帽)
        UIImage *newImage = [image stretchableImageWithLeftCapWidth:20 topCapHeight:0];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 220, size.height + 20)];
        imageView.image = newImage;
        [view addSubview:imageView];
    }
    
    //显示文字的label
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 200, size.height + 10)];
    label.font = font;
    
    label.text = message;
    label.backgroundColor = [UIColor clearColor];
    label.numberOfLines = 0;
    [view addSubview:label];
    
    return view;
}

#pragma mark---键盘的监听事件
// 键盘弹出时 相应的事件
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    [self keyboardDidShow:nil];
    return YES;
}
// 键盘消失的时候 响应的事件
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    [self keyboardDidHidden];
    return YES;
}
// 收回键盘的时候调用
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [_txContent becomeFirstResponder];
    return YES;
}
// 键盘弹出时
-(void)keyboardDidShow:(NSNotification *)notification{
    
    //获取键盘高度
    NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect;
    
    [keyboardObject getValue:&keyboardRect];
    
    //调整放置有textView的view的位置
    //设置动画
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    
    
    if (version>=7) {
        if (Kheight == 568) {
            //设置发布的按钮网上移动
            int autoHeight = Kheight - 20 - 68 - keyboardRect.size.height + 10;//高度
            willSendMsg.frame = CGRectMake(0, autoHeight + 20, Kwidth, 68);
            _tabForMessage.frame = CGRectMake(0, 64, Kwidth, autoHeight - 44);
            _tabForMessage.contentOffset = CGPointMake(0, _tabForMessage.contentSize.height-568+50+280);

        }else{
//            //设置发布的按钮网上移动
//            int autoHeight = Kheight - 49 - 68 - keyboardRect.size.height + 10;//高度
//            willSendMsg.frame = CGRectMake(0, autoHeight+49, Kwidth, 68);
//            _tabForMessage.frame = CGRectMake(0, 64, Kwidth, autoHeight);
//            _tabForMessage.contentOffset = CGPointMake(0, _tabForMessage.contentSize.height-468+50+280);

            //设置发布的按钮网上移动
            int autoHeight = Kheight - 20 - 68 - keyboardRect.size.height + 10;//高度
            willSendMsg.frame = CGRectMake(0, autoHeight + 20, Kwidth, 68);
            _tabForMessage.frame = CGRectMake(0, 64, Kwidth, autoHeight - 44);
            _tabForMessage.contentOffset = CGPointMake(0, _tabForMessage.contentSize.height-Kheight+50+280);

        }
        
    }else{
        //设置发布的按钮网上移动
        int autoHeight = Kheight - 49 - 68 - keyboardRect.size.height + 10;//高度
        willSendMsg.frame = CGRectMake(0, autoHeight + 20, Kwidth, 68);
        _tabForMessage.frame = CGRectMake(0, 24, Kwidth, autoHeight );
        _tabForMessage.contentOffset = CGPointMake(0, _tabForMessage.contentSize.height-468+50+280);
    }
    [UIView commitAnimations];
}
//键盘消失时
-(void)keyboardDidHidden {
    if (version>=7){
        if (Kheight == 568) {
            int autoHeight = Kheight - 20 - 51 - 68;
            _tabForMessage.frame = CGRectMake(0, 64, Kwidth, autoHeight - 44);
            willSendMsg.frame = CGRectMake(0, autoHeight + 24, Kwidth, 68);
        }else{
//            int autoHeight = Kheight- 68-51;
//            _tabForMessage.frame = CGRectMake(0, 64, Kwidth, Kheight-68-49-64);
//            willSendMsg.frame = CGRectMake(0, autoHeight+10 , Kwidth, 68);
            
            int autoHeight = Kheight - 20 - 51 - 68;
            _tabForMessage.frame = CGRectMake(0, 64, Kwidth, autoHeight-44);
            willSendMsg.frame = CGRectMake(0, autoHeight + 24, Kwidth, 68);

        }
    }else{
        int autoHeight = Kheight - 49 - 68-44;
        _tabForMessage.frame = CGRectMake(0, 24, Kwidth, autoHeight);
      
        willSendMsg.frame = CGRectMake(0, autoHeight + 24, Kwidth, 68);
    }
    
}
#pragma mark 手势点击事件，让输入框不在成为第一响应者
-(void)handleSingle:(UITapGestureRecognizer *)sender {
    [_txContent resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
